import cv2
import numpy as np
import struct
import time


def encode(bin_file: str, img_shape: tuple):
    n = 0
    rows, cols = img_shape
    row, col = 0, 0
    imageRead = np.zeros((rows, cols, 3), np.uint8)
    with open(bin_file, 'rb') as fileReader:
        item = fileReader.read(1)
        while item:
            Byte = struct.unpack('B', item)
            Byte = Byte[0]
            for i in range(8):
                imageRead[row, col] = (255, 255, 255) if Byte % 2 == 1 else (0, 0, 0)
                Byte //= 2
                col += 1
                if col == cols:  # 换行
                    col = 0
                    row += 1
                    if row == rows:  # 换图
                        row = 0
                        cv2.imwrite('pic/pic' + str(n) + '.png', imageRead)
                        imageRead = np.zeros((rows, cols, 3), np.uint8)
                        n += 1
            item = fileReader.read(1)
        if row != 0 or col != 0:
            cv2.imwrite('pic/pic' + str(n) + '.png', imageRead)


def img2video(video_file: str, fps: float, num_of_frames: int):
    fourcc = cv2.VideoWriter_fourcc('I', '4', '2', '0')
    Video_Writer = cv2.VideoWriter(video_file, fourcc, fps, (240, 135), True)
    for i in range(num_of_frames):
        frame = cv2.imread('pic/pic' + str(i) + '.png')
        Video_Writer.write(frame)
    Video_Writer.release()


if __name__ == '__main__':
    # decode('source.jpg', 'source.bin')

    # encode
    bin_file = input('请输入二进制文件名:')  # source.bin
    video_file = input('请输入视频文件名:')  # video.avi
    video_len = int(input('请输入编码后的视频长度(秒):'))  # 10

    start_time = time.time()
    encode(bin_file, img_shape=(135, 240))
    print('Finish encoding.')
    img2video(video_file, fps=24 / video_len, num_of_frames=24)
    print('Finish convert image to video.')
    print('波特率:', (95 * 1000) / (time.time() - start_time), 'bps')
